var Tweetflower = function() {
	var tweets = [];
	var isUserScroll = true;
	
	handleDocumentScrolling = function(data) {
		
		if(!isUserScroll) {
			console.log("programatic scrolling");
			return;
		}

		var pos = $(document).scrollTop();
		//check if scrolled topmost
		if(pos <= 0) {
			var topId=tweets[0].id_str;
			authAgainstTwitter(topId);
			$("#statusbar_top").css({
				visibility : "visible"
			});
			$("#statusbar_top").animate({
				height : 40
			}, 500);
		} else {
			// check if scrolled to bottom most position
			if(pos + $(window).height() >= $(document).height() && document.height > $(window).height()) {
				isUserScroll = false;
				$("#statusbar_bottom").css({
					visibility : "visible"
				});
				$("#statusbar_bottom").animate({
					height : 100
				}, 500, function() {
					$(document).scrollTop(pos + 100);
					isUserScroll = true;
				});
				// todo: don't just fetch current top20, but older than the last one.
				var lastId=tweets[tweets.length - 1].id_str;
				authAgainstTwitter(0,lastId);
			}
		}
	};
	
	handleTweets = function(data, textStatus, jqXHR) {

		
        if(!data.length && typeof(data.length)!='number'){
        	// no data array fetched, error so relogin!
        	console.log(data);
        	alert("no data was received, please login again!");
        	showLogin();
        }
        
        console.log("data cnt: " + data.length);
		
		
		$(data).each(function(i, tweet) {
			
			// set proper time string instead of timestamp
			timestamp = new Date(Date.parse(tweet["created_at"]));
			tweet["created_at"] = timestamp.toLocaleTimeString() + " " + timestamp.toLocaleDateString();
			
			// apply tweetflow translation
			var tf = parseTweetflow(tweet.text);
			if(tf){
				tweet.tweetflow=tf;
				tweet.tweetflowTranslation = translateTFtoNaturalEnglish(tf);
			}
		});
		
			if(tweets.length > 0 && data.length > 0)
			{
				if(data[0].id > tweets[0].id)
				{
					console.log("inserting new tweets on top");
					tweets = data.concat(tweets);
				}
				else if(data[0].id == tweets[tweets.length- 1].id){
					// workaround for tweet id problem, querying with same oldest id
					// => getting oldest tweet again, so filter this shit out
					data.shift();
					console.log("filter duplicate and inserting older tweets on bottom");
					tweets = tweets.concat(data);
				}
			}
			else
			{
				console.log("inserting older tweets on bottom");
				tweets = tweets.concat(data);
			}
				
		  
		

		//$("#tweets").link(tweets, "tweetTemplate");
		$("#tweets").html($.render(tweetTemplate, tweets));

		// linkify tweets
		$(".tweettext").each(function(i, div) {
			var text = div.innerHTML.linkify();
			div.innerHTML = text;
		})
		
		// linkify tweets
		$(".tweetflowtext").each(function(i, div) {
			var text = div.innerHTML.linkify();
			div.innerHTML = text;
		})
		
		// text rendering logic
		twttr.anywhere(function(T) {
			T.hovercards();
		});
		// statusbar logic
		isUserScroll = false;
		$("#statusbar_bottom").animate({
			height : 0
		}, 500, function() {
			$("#statusbar_bottom").removeAttr("style");
			isUserScroll = true;
		});

		$("#statusbar_top").animate({
			height : 0
		}, 500, function() {
			$("#statusbar_top").removeAttr("style");
		});

		$("title").text("TweetFlower");

		$("div.tweetflow").mouseenter(function() {

			var pos = $(this).offset();

			pos.left += $(this).width() + 20;
			$("#infopanel").offset(pos);
			$("#infopanel").css({
				height : $(this).height() + 20
			});
			
			var remainingWidth=window.innerWidth - 480;
			var infopanelWidth= 400;
			if(remainingWidth < infopanelWidth){
				infopanelWidth = remainingWidth;
			}
			
			$("#infopanel").animate({
				width : infopanelWidth
			}, 100);
			
			
			// show original tweet in infopanel
			$("#originaltext").text($(this).find(".hiddentweettext").text());
		});

		$("div.tweetflow").mouseleave(function() {
			$("#infopanel").css({
				width : 0
			});
			
			// needed because of twittr anywhere -> shows username hovercard when actually hidden!
			$("#originaltext").text("none.");
		});
	}

    showLogin = function() {
    	window.location = config.loginUrl;
    }

	authAgainstTwitter = function(since_id, max_id) {
		$("title").text("loading from twitter...");
		console.log("contacting twitteroauth");
		var request_prams="";
		if(since_id && typeof(since_id)=='string'){
			//since_id = parseInt(since_id);
			request_prams += "since_id="+ since_id +"&";
		}
		if(max_id && typeof(max_id) == 'string'){
			//max_id= parseInt(max_id);
			request_prams += "max_id=" + max_id;
		}
		var jqxhr = $.getJSON(config.twitterOauthBackendUrl+request_prams);
		jqxhr.success(handleTweets);
		jqxhr.error(function(data) { 
			showLogin();
		})
	};
	
	$(document).ready(authAgainstTwitter);
	$(document).scroll(handleDocumentScrolling);
	
	
	this.getTweet = function(index){
		return tweets[index];
	}
};
